package cMiddleware

import (
	"fmt"

	"github.com/gin-gonic/gin"

	"gitee.com/csingo/cLog"
)

func GetGinHandlerFunc(app, name string, params MiddlewareParams) (gin.HandlerFunc, error) {
	var result gin.HandlerFunc
	var err error

	index := app + "." + name
	instance := container.Get(index)

	if instance == nil {
		cLog.WithContext(nil, map[string]any{
			"source": "cMiddleware.GetGinHandlerFunc",
			"app":    app,
			"name":   name,
		}).Error("获取 middleware 异常")
		err = fmt.Errorf("获取 middleware 异常")
		return result, err
	}

	result = func(ctx *gin.Context) {
		e := instance.(MiddlewareInterface).Handler(ctx, params)
		if e != nil {
			cLog.WithContext(ctx, map[string]any{
				"source": "cMiddleware.GetGinHandlerFunc",
				"app":    app,
				"name":   name,
				"result": e.Error(),
			}).Error("middleware handler 执行异常")
			if container.errorHandler != nil {
				container.errorHandler(ctx, e)
			}
			if !ctx.IsAborted() {
				ctx.Abort()
			}
		}
	}

	return result, err
}

func SetErrorHandler(f func(ctx *gin.Context, err error)) {
	container.SetErrorHandler(f)
}
